import { ArgumentsHost, Catch, ExceptionFilter, HttpException, UnauthorizedException } from '@nestjs/common'
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const status = exception.getStatus()
    const exceptionResponse = exception.getResponse()

    let message = ''
    const isLoginRequired = exception instanceof UnauthorizedException && ['请先登录', '无效的token或已过期'].includes(exception.message)

    // 处理验证错误
    if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
      // 处理数组形式的错误消息（如 class-validator 的验证错误）
      if (Array.isArray(exceptionResponse['message']) && exceptionResponse['message'].length > 0) {
        message = exceptionResponse['message'][0]
      }
      // 处理单个字符串形式的错误消息
      else if (typeof exceptionResponse['message'] === 'string') {
        message = exceptionResponse['message']
      }
      else {
        message = exception.message
      }
    } else {
      // 处理非对象类型的错误消息
      message = exception.message
    }

    const errResponse = {
      data: {},
      msg: message,
      code: -1,
    }

    // 会话已过期
    if (isLoginRequired) {
      response.setHeader('X-Session-Expired', 'true')
    }

    response.status(status)
    response.setHeader('Content-Type', 'application/json; charset=utf-8')
    response.send(errResponse)
  }
}